/**
 * 
 */
package org.t2.backstage.module.difchannel.mz;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.gaming.ruler.util.HttpUtil;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.tool.DateTimeUtil;
import org.gaming.tool.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.foundation.starting.ApplicationSettings;
import org.t2.backstage.module.difchannel.mz.MzProtocol.MzApiLoginResponse;
import org.t2.backstage.module.difchannel.mz.MzProtocol.MzApiRechargeRequest;
import org.t2.backstage.module.difchannel.mz.model.MzSetting;
import org.t2.backstage.module.difchannel.mz.service.MzSettingService;
import org.t2.backstage.module.player.model.Player;
import org.t2.backstage.module.player.service.PlayerService;
import org.t2.backstage.module.recharge.model.RechargeCallback;
import org.t2.backstage.module.recharge.service.RechargeCallbackService;
import org.t2.backstage.module.recharge.service.RechargeStatus;

import com.google.gson.reflect.TypeToken;

import sh.t2.share.apiutil.ApiUtil;
import sh.t2.share.module.difchannel.mz.MzApiResponse;
import sh.t2.share.module.difchannel.mz.MzLoginResponse;
import sh.t2.share.module.recharge.RechargeExtra;

/**
 * 
 */
@Controller
public class MzApiController {

	private static Logger logger = LoggerFactory.getLogger(MzApiController.class);
	
	@Autowired
	private MzSettingService mzSettingService;
	@Autowired
	private ApplicationSettings applicationSettings;
	@Autowired
	private PlayerService playerService;
	@Autowired
	private RechargeCallbackService rechargeCallbackService;
	
	@ApiDocument("登录验证，给游戏客户端请求用的")
	@RequestMapping(value = "/api/mz/login")
	@ResponseBody
	public MzApiLoginResponse login(@RequestParam("accessToken") String accessToken) {
		MzSetting mzSetting = mzSettingService.getSetting();
		
		Map<String, Object> map = new HashMap<>();
		map.put("pid", mzSetting.getPid());
		map.put("gid", mzSetting.getGid());
		map.put("access_token", accessToken);
		map.put("tm", DateTimeUtil.currSecond());
		String waitSign = ApiUtil.jointKeyValueToSource(map, mzSetting.getGameKey(), "=", "&");
		String sign = ApiUtil.buildSign(waitSign);
		map.put("sign", sign);
		
		Map<String, String> header = new HashMap<>();
		header.put("content-type", "application/x-www-form-urlencoded");
		String mzResponse = HttpUtil.formPost(mzSetting.getLoginUrl(), map, "UTF-8", header);
		
		logger.info("MZ登录验证签名原文：{}", waitSign);
		logger.info("MZ登录验证签名：{}", sign);
		logger.info("MZ登录验证响应：{}", mzResponse);
		
		MzApiResponse<MzLoginResponse> mzApiResponse = GsonUtil.parseJson(mzResponse,
				TypeToken.getParameterized(MzApiResponse.class, MzLoginResponse.class));
		MzApiLoginResponse response = new MzApiLoginResponse();
		if(mzApiResponse.getCode() == 200) {
			response.uid = mzApiResponse.getData().getUid();
		} else {
			response.uid = "";
		}
		return response;
	}
	
	public static void main(String[] args) {
//		Map<String, Object> map = new HashMap<>();
//		map.put("pid", "101");
//		map.put("gid", "100052");
//		map.put("my_order_no", "M2024071700000245203");
//		map.put("game_order_no", "R2024071710474369611794");
//		map.put("uid", "241856");
//		map.put("order_status", "1");
//		map.put("tm", "1721185177");
//		map.put("amt", "1.00");
//		map.put("game_ext", "product=19#order=R2024071710474369611794#money=1#open=241856#player=335880099201047#sign=12f3da7a1bc17ef9730d0da0293993da#lv=0#vip=0#");
//		map.put("server_id", "7");
//		map.put("server_name", "S7");
//		map.put("role_id", "335880099201047");
//		map.put("role_name", "完美的寒星");
//		String waitSign = ApiUtil.jointKeyValueToSource(map, "1WlqQtx4VbpRPB5oavmk8sIz0XSj7iUE", "=", "&");
//		String localSign = ApiUtil.buildSign(waitSign);
//		System.out.println("localSign " + localSign);
		
		
//		product=19#order=R2024071710474369611794#money=1#open=241856#player=335880099201047#sign=12f3da7a1bc17ef9730d0da0293993da#lv=0#vip=0#
//		1241856R202407171047436961179433588009920104719zhaizi_t2_2024
//		1241856R202407171047436961179433588009920104719zhaizi_t2_2024
		RechargeExtra rechargeExtra = RechargeExtra.decode("product=19#order=R2024071710474369611794#money=1#open=241856#player=335880099201047#sign=12f3da7a1bc17ef9730d0da0293993da#lv=0#vip=0#");
		System.out.println(GsonUtil.toJson(rechargeExtra));
		String localExtraSign = rechargeExtra.buildSign("zhaizi_t2_2024");
		System.out.println(localExtraSign);
		System.out.println(rechargeExtra.getSign());
	}
	
	@ApiDocument("充值回调，给mz渠道回调使用")
	@RequestMapping(value = "/api/mz/recharge")
	@ResponseBody
	public String recharge(MzApiRechargeRequest request) {
		MzSetting mzSetting = mzSettingService.getSetting();
		
		logger.info("收到充值回调: {}", GsonUtil.toJson(request));
		
		Map<String, Object> map = new HashMap<>();
		map.put("pid", request.pid);
		map.put("gid", request.gid);
		map.put("my_order_no", request.my_order_no);
		map.put("game_order_no", request.game_order_no);
		map.put("uid", request.uid);
		map.put("order_status", request.order_status);
		map.put("tm", request.tm);
		map.put("amt", request.amt);
		map.put("game_ext", request.game_ext);
		if(request.getServer_id() != null) {
			map.put("server_id", request.getServer_id());
		}
		if (request.getServer_name() != null) {
			map.put("server_name", request.getServer_name());
		}
		if (request.getRole_id() != null) {
			map.put("role_id", request.getRole_id());
		}
		if (request.getRole_name() != null) {
			map.put("role_name", request.getRole_name());
		}
		
		String waitSign = ApiUtil.jointKeyValueToSource(map, mzSetting.getPayKey(), "=", "&");
		String localSign = ApiUtil.buildSign(waitSign);
		String sign = request.sign;
		logger.info("MZ充值回调签名原文：{}", waitSign);
		logger.info("MZ充值回调签名：{}", sign);
		logger.info("MZ充值回调本地签名：{}", localSign);
		
		RechargeCallback recharge = new RechargeCallback();
		try {
			recharge.setCallbackData(GsonUtil.toJson(request));
			
			BigDecimal bigPayMoney = new BigDecimal(request.amt).multiply(new BigDecimal("100"));
			//单位分
			long payMoney = bigPayMoney.longValue();
			
			String sdkOrderId = request.my_order_no;
			String gameOrderId = request.game_order_no;
			
			String decodeExt = request.game_ext;
			try {
				decodeExt = URLDecoder.decode(decodeExt, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			//验签扩展参数
			RechargeExtra rechargeExtra = RechargeExtra.decode(decodeExt);
			String localExtraSign = rechargeExtra.buildSign(applicationSettings.getBackstageKey());
			
	        //验签数据
	        recharge.setSign(sign);
	        recharge.setLocalSign(localSign);
	        recharge.setExtraSign(rechargeExtra.getSign());
	        recharge.setLocalExtraSign(localExtraSign);
	        recharge.setAllCheck(true);
	        
	        if(localSign.equals(sign)) {
	        	recharge.setRemark("验签通过");
	        } else {
	        	recharge.setRemark("验签不通过");
	        	recharge.setAllCheck(false);
	        }
	        if(localExtraSign.equals(rechargeExtra.getSign())) {
	        	recharge.setRemark("扩展验签通过");
	        } else {
	        	recharge.setRemark("扩展验签不通过");
	        	recharge.setAllCheck(false);
	        }
	        //配置里面填的单位是元
	        if(payMoney == rechargeExtra.getMoney() * 100) {
	        	recharge.setRemark("金额一致");
	        } else {
	        	recharge.setRemark("金额不一致");
	        	recharge.setAllCheck(false);
	        }
	        
	        //获取请求IP
			recharge.setSdkOrderId(sdkOrderId);
			recharge.setGameOrderId(gameOrderId);
			
			Player player = playerService.getEntity(rechargeExtra.getPlayerId());
			recharge.setPlayerId(rechargeExtra.getPlayerId());
			if(player != null) {
				recharge.setNick(player.getNick());
				recharge.setPlatformId(player.getPlatformId());
				recharge.setChannelId(player.getChannelId());
				recharge.setServerId(player.getServerId());
			}
			recharge.setOpenId(rechargeExtra.getOpenId());
			
			recharge.setMoney(payMoney);
			recharge.setProductId(rechargeExtra.getProductId());
		} catch (Exception e) {
			logger.error("", e);
			return "fail";
		} finally {
			rechargeCallbackService.insert(recharge);
		}
		RechargeStatus rechargeStatus = rechargeCallbackService.handleCallback(recharge);
		if(rechargeStatus == RechargeStatus.SUCCESS || rechargeStatus == RechargeStatus.REPEATED) {
			return "success";
		} else {
			return "fail";
		}
	}
}
